﻿package src.utils 
{
	import flash.display.MovieClip;
	import flash.events.Event;
	import src.data.ConfigData;
	import src.data.Categories;
	import src.data.Category;
	import src.data.SubSection;
	import src.utils.XMLimport;
	
	/**
	 * ...
	 * @author hrh - 2009
	 */
	
	public class MultiLoader extends MovieClip
	{
		private var feedImport:XMLimport;
		private var categoryArray:Array;
		private var index:int;
		private var config:ConfigData;
		private var aList:Array;
		
		private var categoryObject:Array;
		private var tempArray:Array;
		
		public function MultiLoader(con:ConfigData)
		{
			config = con;
			
			feedImport = new XMLimport(config);
			feedImport.addEventListener(Event.COMPLETE, onLoadCompleteHandler);
			
			categoryObject = new Array;
			categoryArray = new Array;
			tempArray = new Array;
			
			index = 0;
		}
		
		public function load(aCat:Array)
		{
			var indexArray:Array = new Array;
			tempArray = aCat;
			
		
			for each(var oCat:Categories in aCat)
			{
				indexArray.push(oCat.id);
				
				
				for each(var oSubSection:SubSection in oCat.subSection)
				{
					indexArray.push(oSubSection.id);
				}
			}
			
			categoryArray = indexArray;
			
			loadSequence();
		}
		
		public function get list():Array
		{
			return aList;
		}
		
		private function loadSequence()
		{	
			if (index < categoryArray.length)
			{
				var sCategory:String = config['category'] +  categoryArray[index];
				
				feedImport.load(sCategory, 'category');
			}
			else
			{
				parseData();
			}
		}
		
		private function onLoadCompleteHandler(e:Event)
		{
			if (feedImport.feedlist != null)
			{
				categoryObject[index] = [categoryArray[index],feedImport.feedlist];
			}
			
			index++;
			
			loadSequence();
		}
		
		private function parseData()
		{
			var z:int = 0;
			
			for each(var oCat:Categories in tempArray)
			{
				for (var i:int = 0; i < categoryObject.length;i++)
				{
					if (oCat.id == categoryObject[i][0])
					{
						tempArray[z].category = categoryObject[i][1];
					}
				}
				
				var o:int = 0;
				
				for each(var oSub:SubSection in oCat.subSection)
				{
					for (var x:int = 0; x < categoryObject.length; x++)
					{
						if (oSub.id == categoryObject[x][0])
						{
							tempArray[z].subSection[o].category = categoryObject[x][1];
						}
					}
					o++;
				}
				
				z++;
			}
			
			aList = tempArray;
			
			dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}